import { defineStore } from 'pinia';
import { login, register, updateUser, getUserInfo } from '@/api/userService.js';
import router from '@/router';


export const useUserStore = defineStore('user', {
  state: () => ({
    user: null,
    isAuthenticated: false  
  }),
  actions: {
    async loginUser(userid, password) {
      try {
        const response = await login(userid, password);
        this.user = response.data?.user || { userid };
        this.isAuthenticated = true;

        localStorage.setItem('user', JSON.stringify(this.user));
        localStorage.setItem('isAuthenticated', this.isAuthenticated);

        return response;
      } catch (error) {
        if (error.message === '操作成功') {
          this.user = { userid };
          this.isAuthenticated = true;

          localStorage.setItem('user', JSON.stringify(this.user));
          localStorage.setItem('isAuthenticated', this.isAuthenticated);

          return { data: { user: { userid } } };
        }
        throw error;
      }
    },
    // 注册用户
    async registerUser(userData) {
      const response = await register(userData);
      return response;
    },
    // 修改用户信息
    async updateUserInfo(userid, updateData) {
      const response = await updateUser(userid, updateData);
      if (this.user?.userid === userid) {
        this.user = { ...this.user, ...updateData };
        localStorage.setItem('user', JSON.stringify(this.user));
      }
      return response;
    },
    // 获取用户信息
    async fetchUserInfo(userid) {
      try {
        const response = await getUserInfo(userid);
        console.log('store 中接收到的用户信息:', response.data); // 检查 store 中接收到的用户信息
        this.user = response.data?.data || response.data;
        localStorage.setItem('user', JSON.stringify(this.user));
        return response;
      } catch (error) {
        console.error('在 store 中获取用户信息失败:', error);
        throw error;
      }
    },
    // 退出登录
    logout() {
      this.user = null;
      this.isAuthenticated = false; 

      localStorage.removeItem('user');
      localStorage.removeItem('isAuthenticated');
      router.push('/main');
    },
    checkAuth() {
      const storedUser = localStorage.getItem('user');
      const storedIsAuthenticated = localStorage.getItem('isAuthenticated');
      if (storedUser && storedIsAuthenticated === 'true') {
        this.user = JSON.parse(storedUser);
        this.isAuthenticated = true;
      } else {
        this.user = null;
        this.isAuthenticated = false;
      }
    }
  },
  getters: {
    fullName: (state) => {
      if (!state.user) return '';
      return `${state.user.firstname} ${state.user.lastname}`;
    },
    // 添加一个 getter 来获取 userId
    userId: (state) => {
      return state.user?.userid;
    }
  }
});